#include "common.h"

void CMD_RM(const char *name);
void RmDir(const char *dname);
void RmFile(const char *fname);

int main(int argc, char *argv[]) {
    CMD_RM(argv[1]);
    return 0;
}

//删除文件
void CMD_RM(const char* name) {
	printf(">> Start RM.\n");
	struct stat statbuf;
	int ret = stat(name, &statbuf);
	ERROR_CHECK(ret, -1, "stat");

	if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
		//注意把文件夹内的文件删除后还要删除文件夹本身
        RmDir(name);
        rmdir(name);
	} else {
		RmFile(name);
	}
	printf(">> Finish RM.\n");
}

void RmDir(const char* dname) {
	DIR* pdir = opendir(dname);
	ERROR_CHECK(pdir, NULL, "opendir");

	struct dirent* pdirent;
	struct stat statbuf;
	errno = 0;
	while ((pdirent = readdir(pdir)) != NULL) {
		if (errno != 0) {
			closedir(pdir);
			perror("readdir");
			exit(1);
		}
		//忽略上级目录和本级目录，不忽略会一直出错
		char* name = pdirent->d_name;
		if ((strcmp(name, ".") == 0) || (strcmp(name, "..") == 0)) {
			continue;
		}

		//拼接文件名，避免在本文件夹中无法删除其他文件夹现象出现
		char pathname[1024];
		sprintf(pathname, "%s/%s", dname, name);

		int ret = stat(pathname, &statbuf);
		if (ret == -1) {
			closedir(pdir);
			perror("stat");
			exit(1);
		}
        
        //注意要使用文件的绝对路径进行删除
		if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
			RmDir(pathname);
            rmdir(pathname);
		}
		else {
			RmFile(pathname);
		}
    }
    closedir(pdir);
}

void RmFile(const char* fname) {
	int ret = remove(fname);
	ERROR_CHECK(ret, -1, "remove");
}
